﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using DAL;
using CommonUtility;
using System.Text.RegularExpressions;

namespace BLL
{
    public class bllUser
    {

        /// <summary>
        /// 根据userID获取用户
        /// </summary>
        /// <param name="_name"></param>
        /// <returns></returns>
        public static UserInfo GetUser(string _userID)
        {
            UserInfo rUser = new UserInfo();
            IList<UserInfo> Users = User.GetList("userID='" + _userID + "' and flag='A'");
            if (Users.Count > 0)
            {
                rUser = Users[0];
            }
            return rUser;
        }


        /// <summary>
        /// 根据条件获取用户
        /// </summary>
        /// <param name="_key"></param>
        /// <returns></returns>
        public static IList<UserInfo> GetAllUser(string _key)
        {
            IList<UserInfo> list = new List<UserInfo>();
            if (string.IsNullOrEmpty(_key))
                list = User.GetList("");
            else
                list = User.GetList("[UserID] LIKE '%" + _key.Replace("'", "''") + "%' OR [Name] LIKE '%" + _key.Replace("'", "''") + "%'");

            foreach (var user in list)
            {
                IList<UserRoleInfo> urList = UserRole.GetList("[UserID]='" + user.UserID + "'");
                string roleList = string.Join("/", urList.Select(d => d.RoleID).ToArray());
                user.RoleList = roleList;
            }

            return list;
        }



        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="_FunID"></param>
        /// <param name="_User"></param>
        /// <param name="_operater">操作人</param>
        /// <returns></returns>
        public static string SaveUser(string _FunID, UserInfo _User, string _Type, UserInfo _operater)
        {
            string result = string.Empty;
            bool isNew = true;

            System.Data.SqlClient.SqlTransaction myTran = SQLCommon.GetSqlTransaction();
            System.Data.SqlClient.SqlConnection conn = myTran.Connection;
            try
            {
                UserInfo user = User.GetModelByID(string.IsNullOrEmpty(_User.RID.ToString()) ? 0 : Common.ToInt32(_User.RID));
                if (string.IsNullOrEmpty(_User.RID.ToString()) || _User.RID == 0 )
                {
                    IList<UserInfo> old = User.GetList("UserID='" + _User.UserID + "'");
                    if (old.Count > 0)
                        throw new Exception("User ID: " + _User.UserID + " already exists/用户ID:" + _User.UserID + "已存在!");
                }
                else
                {
                    isNew = false;
                }

                _User.Whom = _operater.UserID;
                _User.Pwd = user.Pwd;//密码保存
                User.Add(_User, myTran);

                if (_Type.Equals("1"))
                {
                    if (!isNew)
                        bllUserRole.DeleleByUserID(_User.UserID, myTran);

                    if (!string.IsNullOrEmpty(_User.RoleList))
                    {
                        string[] arrayRLID = _User.RoleList.Split('/');
                        for (int i = 0; i < arrayRLID.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(arrayRLID[i]))
                                bllUserRole.AddUserRole(_User.UserID, arrayRLID[i], _operater.UserID, myTran);
                        }
                    }
                }
                bllLog.AddLog(_FunID, isNew ? "Add" : "Update", _User.UserID.ToString(), _operater.UserID, myTran);
                myTran.Commit();
            }
            catch (Exception ex)
            {
                result = ex.Message;
                myTran.Rollback();
                Common.Application_Error_Server("bllUser.cs/SaveUser() " + _operater.Name, ex);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
                myTran.Dispose();
            }

            return result;
        }

        /// <summary>
        /// 得到所有用户(过滤重复的、无效的)
        /// </summary>
        /// <param name="_id">角色、用户ID组合</param>
        /// <returns></returns>
        public static IList<UserInfo> GetAllUsers(string _id)
        {
            IList<string> userIDs = new List<string>();
            IList<UserInfo> result = new List<UserInfo>();
            if (!string.IsNullOrEmpty(_id))
            {
                string[] ids = _id.Trim().Trim(',').Split(',');
                foreach (string id in ids)
                {
                    if (id.StartsWith("<") && id.EndsWith(">"))
                    {
                        IList<UserInfo> temp = User.GetRoleUsers(id.Trim('<').Trim('>'));
                        foreach (UserInfo user in temp)
                        {
                            if (user.Flag == "A" && !userIDs.Contains(user.UserID.ToString()))
                            {
                                userIDs.Add(user.UserID);
                                result.Add(user);
                            }
                        }
                    }
                    else
                    {
                        UserInfo user =User.GetModelByID(Common.ToInt32(id));
                        if (user.Flag == "A" && !userIDs.Contains(user.UserID.ToString()))
                        {
                            userIDs.Add(user.UserID);
                            result.Add(user);
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 处理用户
        /// </summary>
        /// <param name="_rids">用户记录的RID集合</param>
        /// <param name="_type">处理类型：A、I</param>
        /// <param name="_operater">操作人</param>
        /// <returns></returns>
        public static string ProcessUser(string _funID, string _rids, string _type, UserInfo _operator)
        {
            string result = string.Empty;
            System.Data.SqlClient.SqlTransaction myTran = SQLCommon.GetSqlTransaction();
            System.Data.SqlClient.SqlConnection conn = myTran.Connection;
            try
            {
                string userid = string.Empty;
                IList<UserInfo> userList = User.GetList("[RID] IN(" + _rids + ")");
                foreach (var user in userList)
                {
                    user.Flag = _type;
                    user.Whom = _operator.UserID;
                    User.Edit(user, myTran);
                    userid += user.UserID + ",";
                }
                bllLog.AddLog(_funID, _type == "A" ? "Active" : "Inactive", userid.Trim(','), _operator.UserID, myTran);

                myTran.Commit();
            }
            catch (Exception ex)
            {
                result = ex.Message;
                myTran.Rollback();
                Common.Application_Error_Server("BLL/bllUser.cs/ProcessUser(" + _rids + ") " + _operator.Name, ex);
            }
            finally
            {
                conn.Close();
                myTran.Dispose();
                conn.Dispose();
            }

            return result;
        }


         /// <summary>
        /// 检查邮件格式
        /// </summary>
        /// <param name="_Email"></param>
        /// <returns></returns>
        public static bool CheckEmail(string _Email)
        {
            String strExp = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            Regex r = new Regex(strExp);
            Match m = r.Match(_Email);
            return m.Success;
        }
         
    }
}
